package com.ruoyi.project.system.user.service;

import com.qq.connect.QQConnectException;
import com.qq.connect.api.OpenID;
import com.qq.connect.api.qzone.UserInfo;
import com.qq.connect.javabeans.AccessToken;
import com.qq.connect.javabeans.qzone.UserInfoBean;
import com.qq.connect.oauth.Oauth;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.project.system.user.domain.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private IUserService iUserService;


    /**
     * qq登入
     * @param request
     * @param response
     * @return
     */
    @Override
    public String QQLong(HttpServletRequest request, HttpServletResponse response) {

        User user = null;

        try {
            //创建对象
            AccessToken accessTokenobj = (new Oauth()).getAccessTokenByRequest(request);
            //用户信息和唯一ID
            String accessToken = null, openID = null;
            long tokenExpireIn = 0L;
            //code=E4171093538675B89139C5ACB1FD6955&state=e8457f98419be3a042b890396d46cc51
            if (StringUtils.isEmpty(accessTokenobj.getAccessToken())) {

                throw new BusinessException("没有获取到数据^_^...");

            } else {

                accessToken = accessTokenobj.getAccessToken();
                tokenExpireIn = accessTokenobj.getExpireIn();
                // 利用获取到的accessToken 去获取当前用的openid -------- start
                OpenID openIDObj = new OpenID(accessToken);
                openID = openIDObj.getUserOpenID();
                UserInfo qzoneUserInfo = new UserInfo(accessToken, openID);
                UserInfoBean userInfoBean = qzoneUserInfo.getUserInfo();

                if (userInfoBean.getRet() == Constants.IntegerStatusUtils.zero) {

                    User selectUser = iUserService.selectUserByLoginName("qq-" + openID);

                    /*没有查找到用户 */
                    if (ObjectUtils.isEmpty(selectUser)) {
                        user = new User();
                        /*随机生成盐*/
                       // user.randomSalt();

                        //qq用户唯一识别的id
                        user.setPassword(openID);
                        //qq用户的名字
                        user.setUserName(StringUtils.isEmpty(userInfoBean.getNickname().trim()) ? "匿名" : userInfoBean.getNickname());
                        //用户的头像
                        user.setAvatar(userInfoBean.getAvatar().getAvatarURL30());
                        //男女
                        user.setSex(userInfoBean.getGender());

                        /*用户角色*/
                        user.setRoleIds(new Long[]{3L});
                        /*相关部门qq用户*/
                        user.setDeptId(103L);
                        //注册类型
                        user.setUserType("QQ");
                        //注册时间
                        user.setCreateTime(DateUtils.getNowDate());


                        int integer = iUserService.insertUser(user);

                        if (integer != Constants.IntegerStatusUtils.one) {
                            throw new BusinessException("登入失败^_^...");
                        }
                        /*shiro 登入*/
                        qqLogin(user.getLoginName(), user.getPassword(), true);
                    } else {

                        qqLogin(user.getLoginName(), user.getPassword(), true);

                    }

                } else {
                    throw new BusinessException("很抱歉，我们没能正确获取到您的信息，原因是" + userInfoBean.getMsg());
                }
            }

        } catch (QQConnectException e) {
            e.printStackTrace();
        }

        return user.getAvatar();
    }

    /**
     * shiro 登入
     *
     * @param username
     * @param password
     * @param rememberMe
     */
    private void qqLogin(String username, String password, Boolean rememberMe) {

        UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
        } catch (AuthenticationException e) {
            String msg = "用户或密码错误";
            if (com.ruoyi.common.utils.StringUtils.isNotEmpty(e.getMessage())) {
                msg = e.getMessage();
            }
            throw new BusinessException(msg);
        }
    }


}
